package libra.controller;

import java.time.LocalDateTime;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.transaction.Propagation;
import libra.model.JsonResult;
import libra.model.seate.Goods;
import libra.model.seate.GoodsDetails;
import libraServer.dao.Dao;

/**
 * 商品管理控制器
 * @author libra
 */
@RestController
public class GoodsController {
	@Autowired
	Dao dao;
	
	@Value( "#{'${server.servlet.context-path}'.concat('[port(${server.port})]')}" )
	String identity;
	
	/**
	 * 商品库存功能接口
	 * @param goods_id 商品id
	 * @param count 本次操作的商品数量，整数加库存，负数减库存
	 * @param req
	 * @param resp
	 * @return
	 */
	@GlobalTransactional(propagation = Propagation.REQUIRES_NEW)
//	@Transactional(rollbackFor = Exception.class)
	@RequestMapping("stock")
	public JsonResult<?> stock( Integer order_id, Integer goods_id, Integer count, Boolean isEx, HttpServletRequest req, HttpServletResponse resp ) throws Exception {
		// 获取 XID
		String xid = RootContext.getXID();
		System.err.println( "获取XID【GoodsController.stock()】:"+xid );
		// 修改库存
		Goods goods = sql_ModifyGoodsCount(goods_id, count);
		// 记录库存操作流水
		GoodsDetails goodsDetails = sql_RecordModifyDetails( order_id, goods, count);
		
		@SuppressWarnings("unused")
		int i = 1/(isEx?0:1);
		
		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("goodsDetails", goodsDetails.toString() );
		hashMap.put("goods", goods.toString() );
		return new JsonResult<Object>(0, identity, hashMap);
	}
	
	/**
	 * 操作商品库存
	 * @param goods_id 商品id
	 * @param count 操作库存，整数加库存，负数减库存
	 * @throws Exception 
	 */
	public Goods sql_ModifyGoodsCount( Integer goods_id, Integer count ) throws Exception {
		Goods goods = dao.findByPK(Goods.class, goods_id);
		goods.setNum( goods.getNum().intValue()+count.intValue() );
		dao.update(goods);
		return goods;
	}
	
	/**
	 * 记录当前这次的操作流水
	 * @param goods_id 商品id
	 * @param count 操作库存，整数加库存，负数减库存
	 * @throws Exception 
	 */
	public GoodsDetails sql_RecordModifyDetails( Integer order_id, Goods goods, Integer count ) throws Exception {
		GoodsDetails details = new GoodsDetails( order_id, goods.getId(), count, goods.getNum(), LocalDateTime.now().toString());
		dao.save(details);
		return details;
	}
}
